//
//  ExperienceChooseCityViewController.m
//  MemoryTravel
//
//  Created by dllo on 15/12/25.
//  Copyright © 2015年 fcx. All rights reserved.
//

#import "ExperienceChooseCityViewController.h"
#import "CityTableViewCell.h"
#import "HotCityTableViewCell.h"

@interface ExperienceChooseCityViewController()<UITableViewDataSource, UITableViewDelegate, HotCityTableViewCellDelegate>

@property (nonatomic, strong)UITableView *myTableView;

@property (nonatomic, strong)NSMutableArray *cityArray;
@property (nonatomic, strong)NSMutableArray *hots;

@end

@implementation ExperienceChooseCityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:65 / 255.0 green:176 / 255.0 blue:194 / 255.0 alpha:1.0];
    
    self.cityArray = [NSMutableArray array];
    self.hots = [NSMutableArray array];
    
    [[DataBaseTools shareDataBase] openDB];
    self.hots = [[DataBaseTools shareDataBase] selectCityArrayWithType:@"热门"];
    self.cityArray = [[DataBaseTools shareDataBase] selectCityArrayWithType:@"全部"];
    
    
    UILabel *headLabel = [UILabel new];
    headLabel.text = @"选择城市";
    headLabel.font = [UIFont systemFontOfSize:20];
    headLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:headLabel];
    
    [headLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(50);
    }];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [backButton setBackgroundImage:[UIImage imageNamed:@"iconfont-x.png"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self.view.mas_centerX);
        make.bottom.mas_equalTo(-40);
    }];
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 110, Width, Height - 110 - 100) style:UITableViewStylePlain];;
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    self.myTableView.backgroundColor = [UIColor colorWithRed:65 / 255.0 green:176 / 255.0 blue:194 / 255.0 alpha:1.0];
    self.myTableView.showsVerticalScrollIndicator = NO;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UILabel *gpsLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, Width, 30)];
    gpsLabel.font = [UIFont systemFontOfSize:14];
    if (self.city == nil) {
        gpsLabel.textColor = [UIColor colorWithRed:130 / 255.0 green:208 / 255.0 blue:216 / 255.0 alpha:1.0];
        gpsLabel.text = @"    GPS 定位失败";
    }
    else {
        gpsLabel.textColor = [UIColor whiteColor];
        NSString *tempString = [NSString stringWithFormat:@"    %@ GPS 定位", self.city];
        NSMutableAttributedString *attrituteString = [[NSMutableAttributedString alloc] initWithString:tempString];
        NSRange range = [tempString rangeOfString:@"GPS 定位"];
        [attrituteString setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:130 / 255.0 green:208 / 255.0 blue:216 / 255.0 alpha:1.0],NSFontAttributeName : [UIFont boldSystemFontOfSize:14]} range:range];
        gpsLabel.attributedText = attrituteString;
        
        gpsLabel.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [gpsLabel addGestureRecognizer:tap];
    }
    
    
    self.myTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Width, 50)];
    [self.myTableView.tableHeaderView addSubview:gpsLabel];
    [self.view addSubview:self.myTableView];
    
//    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.width.mas_equalTo(Width);
//        make.top.mas_equalTo(110);
//        make.bottom.mas_equalTo(-100);
//    }];
    
    [self.myTableView registerClass:[HotCityTableViewCell class] forCellReuseIdentifier:@"hot"];
    [self.myTableView registerClass:[CityTableViewCell class] forCellReuseIdentifier:@"cell"];
    

    NSString *urlStr = @"http://api.breadtrip.com/hunter/products/tabs/v2/";
    [AppTools getDataWithUrlStr:urlStr andBlock:^(id result) {
        NSMutableDictionary *bigDic = result;
        
        [[DataBaseTools shareDataBase] dropCityChooseTable];
        [[DataBaseTools shareDataBase] createCityChooseTbale];
        
        
        NSMutableArray *tempArray = [bigDic objectForKey:@"hot_city_list"];
        NSMutableDictionary *tempDic = [tempArray lastObject];
        self.hots = [NSMutableArray arrayWithArray:[tempDic objectForKey:@"city_list"]];
        [[DataBaseTools shareDataBase] insertHotCitiesWithArray:self.hots];
        
        self.cityArray = [NSMutableArray arrayWithArray:[bigDic objectForKey:@"hunter_city_list"]];
        [[DataBaseTools shareDataBase] insertAllCitiesWithArray:self.cityArray];
        
        [self.myTableView reloadData];
    }];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, Width, 40)];
    if (section == 0) {
        label.text = @"    热门城市";
    } else {
        label.text = @"    全部城市";
    }
    label.textColor = [UIColor colorWithRed:130 / 255.0 green:208 / 255.0 blue:216 / 255.0 alpha:1.0];
    label.font = [UIFont systemFontOfSize:14];
    
    return label;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

#pragma mark - 设置section不粘连
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.myTableView){
        
        CGFloat sectionHeaderHeight = 30; //sectionHeaderHeight
        if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    return self.cityArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        static NSString *cellIdentifier = @"hot";
        HotCityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        cell.myArray = self.hots;
        cell.hotCityTableViewCellDelegate = self;
        
        return cell;
    } else {
        static NSString *cellIdentifier = @"cell";
        CityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        cell.city = [self.cityArray objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 105;
    }
    return 40;
}

- (void)backButtonAction:(UIButton *)button{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)addressPass_:(NSString *)cityName{
    [[NSUserDefaults standardUserDefaults] setValue:cityName forKey:@"localCity"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}

- (void)tapAction:(UITapGestureRecognizer *)tap{
    [[NSUserDefaults standardUserDefaults] setValue:self.city forKey:@"localCity"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        [[NSUserDefaults standardUserDefaults] setValue:[self.cityArray objectAtIndex:indexPath.row] forKey:@"localCity"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self dismissViewControllerAnimated:YES completion:^{
            
            
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
